import {
  accountModelProvider,
  initAccounts,
  signInExpire,
} from '@app/common/constants';
import { Account } from '@app/common/types/account.type';
import { Inject, Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { Model } from 'mongoose';

@Injectable()
export class AccountService {
  constructor(
    @Inject(accountModelProvider)
    private readonly accountModel: Model<Account>,
    private readonly jwtService: JwtService,
  ) {}

  async signIn(
    account: Pick<Account, 'account' | 'password'>,
  ): Promise<string | undefined> {
    const accountDoc = await this.accountModel.findOne(
      { ...account },
      { account: 1, role: 1 },
    );
    if (!!accountDoc) {
      return this.jwtService.sign(
        { ...accountDoc },
        {
          expiresIn: signInExpire,
        },
      );
    }
    return undefined;
  }

  async initData() {
    initAccounts.forEach(async (account) => {
      const accountDoc = await this.accountModel.findOne(account);
      if (!accountDoc) this.accountModel.create(account);
    });
  }

  async hasInitData() {
    return (await this.accountModel.countDocuments()) >= 2;
  }
}
